package com.example.demo.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.entity.BookAssist;
import com.example.demo.entity.BookComment;
import com.example.demo.entity.BookCore;
import com.example.demo.service.BookAssistServiceImpl;
import com.example.demo.service.BookCommentServiceImpl;
import com.example.demo.service.BookCoreServiceImpl;
import com.example.demo.service.BookRecommendServiceImpl;
import com.example.demo.service.UserInforTouristServiceImpl;
import com.example.demo.util.ResultUnify;
import com.example.demo.util.StringUtil;

/**
 * 控制层
 * 
 * @author wang
 */
@RestController
@RequestMapping("/book")
public class BookController {
	@Autowired
	private BookAssistServiceImpl bookAssistServiceImpl;
	@Autowired
	private BookCoreServiceImpl bookCoreServiceImpl;

	@Autowired
	private BookRecommendServiceImpl bookRecommendServiceImpl;

	@Autowired
	private BookCommentServiceImpl bookCommentServiceImpl;
	@Autowired
	private UserInforTouristServiceImpl userInforTouristServiceImpl;

	/**
	 * 
	 * @apiVersion 1.0.0
	 * @apiDescription 查询书的信息接口
	 * @api {get} http://192.168.2.211:8080/book/findBookInfo 查询书的信息接口
	 * @apiParam {int} id 书的id（必传）
	 * @apiParam {int} userId 用户id（必传）
	 * @apiSuccessExample Request-Example:成功
	 * 
	 *                    { errorCode:200, message:'success',data:{} }
	 * @apiSuccessExample Request-Example:失败
	 * 
	 *                    {errorCode:400, message:'查询失败', data:{} }
	 * @apiSuccess {String} errorCode 200（ 成功结果码）
	 * @apiSuccess {String} errorCode 400 （失败结果码）
	 * @apiGroup Book
	 * @apiSampleRequest http://192.168.2.211:8080/book/findBookInfo?id=3&userId=1034006
	 * @param request
	 * @return
	 */
	@RequestMapping("/findBookInfo")
	public ResultUnify findBookInfo(Integer id, Integer userId) {
		ResultUnify result = new ResultUnify();

		if (StringUtil.isEmpty(id, userId)) {
			return result.custom(null, 415, "缺少毕传参数...");
		}

		BookCore bookCore = new BookCore();
		bookCore.setPageview(1);
		bookCore.setId(id);

		bookCoreServiceImpl.updateByObject(bookCore);

		// 查找书的内容，简介
		bookCore = bookCoreServiceImpl.findById(id);
		if (bookCore == null) {
			return result.custom(null, 400, "查无此书...");
		}
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("bookId", id);

		// 书推荐语
		bookCore.setBookRecommendList(bookRecommendServiceImpl.listByMap(paramMap));

		paramMap.put("type", 0);

		// 根据书id查评论集合
		List<BookComment> bookCommentList = bookCommentServiceImpl.listByMap(paramMap);

		// 处理书的总分
		bookCore.setGradeTotal(bookCommentServiceImpl.getByMapGradeTotal(paramMap).toString());
		// 处理书的平均分
		bookCoreServiceImpl.commmentGradeAvg(bookCore, paramMap);

		// 处理书下的百分比信息
		bookCoreServiceImpl.bookPercent(bookCore, bookCommentList, paramMap);

		// 处理评论下的信息
		bookCoreServiceImpl.commentContent(bookCore, bookCommentList, paramMap);

		return result.custom(bookCore, 200, "查询成功");

	}

	/**
	 * 
	 * @apiVersion 1.0.0
	 * @apiDescription 给书添加评论
	 * @api {get} http://192.168.2.211:8080/book/insertComments 添加评论接口
	 * @apiParam {int} bookId 书的id（必传）
	 * @apiParam {String} content 书的评论（必传）
	 * @apiParam {int} grade 书的评分（必传）
	 * @apiParam {int} userId 用户id（必传）
	 * @apiSuccessExample Request-Example:成功
	 * 
	 *                    { errorCode:200, message:'success',data:{} }
	 * @apiSuccessExample Request-Example:失败
	 * 
	 *                    {errorCode:400, message:'查询失败', data:{} }
	 * @apiSuccess {String} errorCode 200（ 成功结果码）
	 * @apiSuccess {String} errorCode 400 （失败结果码）
	 * @apiGroup InsertComents
	 * @apiSampleRequest http://192.168.2.211:8080/book/insertComments?bookId=3&content=ssss1&grade=9&userId=1034006
	 * @param request
	 * @return
	 */
	@RequestMapping("/insertComments")
	public ResultUnify insertComments(BookComment bookComment) throws Exception {
		ResultUnify result = new ResultUnify();
		String content = bookComment.getContent();
		Integer userId = bookComment.getUserId();
		Integer bookId = bookComment.getBookId();
		Float grade = bookComment.getGrade();
		if (StringUtil.isEmpty(bookId, content, userId, grade)) {
			return result.custom(null, 415, "缺少毕传参数...");
		}

		if (1 > grade || grade > 10) {
			return result.custom(null, 416, "参数错误：评分必须在1到10之间");
		}

		// 查找书的内容，简介
		if (bookCoreServiceImpl.findById(bookId) == null) {
			return result.custom(null, 417, "参数错误：书id有误，书的二维码过去或此书已下架");
		}

		// 一个获取用户的服务。比如返回一个user
		if (userInforTouristServiceImpl.findById(userId) == null) {
			return result.custom(null, 417, "参数错误：用户id有误，此用户不存在");
		}
		// 添加记录
		bookComment.setContent(content).setGrade(grade).setBook_core_id(bookId).setUser_Id(userId).setType(0)
				.setReguseId(0);

		int count = bookCommentServiceImpl.save(bookComment);
		if (count < 1) {
			return result.custom(null, 400, "系统错误：添加评论失败");

		}
		return result.custom(null, 200, "添加评论成功");
	}

	/**
	 * 
	 * @apiVersion 1.0.0
	 * @api {get} http://192.168.2.211:8080/book/addAssist 点赞接口
	 * @apiParam {int} comentId 评论comentId（必传）
	 * @apiParam {int} userId 用户id（必传）
	 * @apiSuccessExample Request-Example:成功
	 * 
	 *                    { errorCode:200, message:'success',data:{} }
	 * @apiSuccessExample Request-Example:失败
	 * 
	 *                    {errorCode:400, message:'查询失败', data:{} }
	 * @apiSuccess {String} errorCode 200（ 成功结果码）
	 * @apiSuccess {String} errorCode 400 （失败结果码）
	 * @apiGroup Select
	 * @apiSampleRequest http://192.168.2.211:8080/book/addAssist?comentId=531&userId=1034002
	 * @param request
	 * @return
	 */
	@RequestMapping("/addAssist")
	public ResultUnify addAssist(BookAssist bookAssist) {

		ResultUnify result = new ResultUnify();
		Integer commentId = bookAssist.getCommentId();
		Integer userId = bookAssist.getUserId();
		if (StringUtil.isEmpty(commentId, userId)) {
			return result.custom(null, 415, "缺少毕传参数...");
		}

		// 一个获取用户的服务。比如返回一个user
		if (userInforTouristServiceImpl.findById(userId) == null) {
			return result.custom(null, 417, "参数错误：用户id有误，此用户不存在");
		}
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("commentId", commentId);
		paramMap.put("userId", userId);
		Long total = bookAssistServiceImpl.getByMapTotal(paramMap);
		
		paramMap.put("type", 0);
		List<BookComment> bookCommentList = bookCommentServiceImpl.listByMap(paramMap);
		if (bookCommentList.size() == 0) {
			return result.custom(null, 417, "参数错误：评论id有误，此评论不存在");
		}
		
		if (total > 0) {
			int i = bookAssistServiceImpl.deleteByObject(bookAssist);
			if (i == 0) {
				return result.custom(null, 400, "点赞取消失败");
			}
			return result.custom(null, 200, "点赞取消成功");
		} else {
			int i = bookAssistServiceImpl.save(bookAssist);
			if (i == 0) {
				return result.custom(null, 400, "点赞失败");
			}
			return result.custom(null, 200, "点赞成功");
		}

	}

	/**
	 * 
	 * @apiVersion 1.0.0
	 * @apiDescription 给评论添加回复
	 * @api {get} http://192.168.2.211:8080/book/insertReply 评论回复接口
	 * @apiParam {int} bookId 书的bookId（必传）
	 * @apiParam {int} userId 用户userId（必传）
	 * @apiParam {int} commentId 评论commentId（必传）
	 * @apiParam {String} content 评论content的内容（必传）
	 * @apiSuccessExample Request-Example:成功
	 * 
	 *                    { errorCode:200, message:'success',data:{} }
	 * @apiSuccessExample Request-Example:失败
	 * 
	 *                    {errorCode:400, message:'查询失败', data:{} }
	 * @apiSuccess {String} errorCode 200（ 成功结果码）
	 * @apiSuccess {String} errorCode 400 （失败结果码）
	 * @apiGroup Comment
	 * @apiSampleRequest http://192.168.2.211:8080/book/insertReply?commentId=531&userId=1000001&bookId=3&content=13131
	 * @param request
	 * @return
	 */
	@RequestMapping("/insertReply")
	public ResultUnify insertReply(BookComment bookComment) {
		ResultUnify result = new ResultUnify();
		String content = bookComment.getContent();
		Integer userId = bookComment.getUserId();
		Integer bookId = bookComment.getBookId();
		Integer commentId = bookComment.getCommentId();
		if (StringUtil.isEmpty(bookId, content, userId, commentId)) {
			return result.custom(null, 415, "缺少毕传参数...");
		}

		// 查找书的内容，简介
		if (bookCoreServiceImpl.findById(bookId) == null) {
			return result.custom(null, 417, "参数错误：书id有误，书的二维码过去或此书已下架");
		}

		// 一个获取用户的服务。比如返回一个user
		if (userInforTouristServiceImpl.findById(userId) == null) {
			return result.custom(null, 417, "参数错误：用户id有误，此用户不存在");
		}
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("commentId", commentId);
		paramMap.put("type", 0);
		List<BookComment> bookCommentList = bookCommentServiceImpl.listByMap(paramMap);
		if (bookCommentList.size() == 0) {
			return result.custom(null, 417, "参数错误：评论id有误，此评论不存在");
		}

		bookComment.setContent(content).setGrade(0f).setBook_core_id(bookId).setUser_Id(userId).setType(commentId)
				.setReguseId(bookCommentList.get(0).getUser_Id());
		// 添加记录
		int count = bookCommentServiceImpl.save(bookComment);
		if (count < 1) {
			return result.custom(null, 400, "系统错误：添加回复失败");
		}
		return result.custom(null, 200, "添加回复成功");
	}
}
